package com.renwenhao.servlet;

import com.renwenhao.dao.LoginDao;
import com.renwenhao.enyity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(value = "/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");
        HttpSession session = request.getSession();
        String checkCode1 = (String) session.getAttribute("checkCode");
        session.removeAttribute("checkCode");
        if(checkCode1 != null && checkCode1.equalsIgnoreCase(checkCode)){
            User user = new User();
            user.setPassword(password);
            user.setUsername(username);
            User u = new LoginDao().getUser(user);
            if(u != null){
                session.setAttribute("user",u.getUsername());
                response.sendRedirect(request.getContextPath()+"/jsp/success.jsp");
            } else {
                request.setAttribute("user_err","用户名密码错误");
                request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            }
        } else {
            request.setAttribute("checkCode_err","验证码错误");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
